package leetcode.code0959;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	int m, n;

	Map<Integer, Integer> map;

	int cnt;

	public int regionsBySlashes(String[] grid) {
		map = new HashMap<>();
		cnt = 0;
		m = grid.length;
		n = grid[0].length();
		for (int i = 0; i < m; i++) {
			String str = grid[i];
			char[] line = str.toCharArray();
			for (int j = 0; j < n; j++) {
				char c = line[j];
				if (c == ' ') {
					this.add(i, j, 0);
					this.merge(i, j, 0, i - 1, j, 0);
					this.merge(i, j, 0, i - 1, j, 2);
					this.merge(i, j, 0, i - 1, j, 3);
					this.merge(i, j, 0, i, j - 1, 0);
					this.merge(i, j, 0, i, j - 1, 2);
					this.merge(i, j, 0, i, j - 1, 4);
				} else if (c == '/') {
					this.add(i, j, 1);
					this.merge(i, j, 1, i - 1, j, 0);
					this.merge(i, j, 1, i - 1, j, 2);
					this.merge(i, j, 1, i - 1, j, 3);
					this.merge(i, j, 1, i, j - 1, 0);
					this.merge(i, j, 1, i, j - 1, 2);
					this.merge(i, j, 1, i, j - 1, 4);
					this.add(i, j, 2);
				} else {
					// \
					this.add(i, j, 3);
					this.merge(i, j, 3, i, j - 1, 0);
					this.merge(i, j, 3, i, j - 1, 2);
					this.merge(i, j, 3, i, j - 1, 4);
					this.add(i, j, 4);
					this.merge(i, j, 4, i - 1, j, 0);
					this.merge(i, j, 4, i - 1, j, 2);
					this.merge(i, j, 4, i - 1, j, 3);
				}
			}
		}
		return cnt;
	}

	private void add(int i, int j, int k) {
		int index = this.index(i, j, k);
		map.put(index, index);
		cnt++;
	}

	private void merge(int i1, int j1, int k1, int i2, int j2, int k2) {
		if (i2 < 0 || j2 < 0) {
			return;
		}
		int index1 = this.index(i1, j1, k1);
		int index2 = this.index(i2, j2, k2);
		int p1 = this.parent(index1);
		int p2 = this.parent(index2);
		if (p1 == -1 || p2 == -1) {
			return;
		}
		if (p1 != p2) {
			map.put(p1, p2);
			cnt--;
		}
	}

	private int parent(int index) {
		if (!map.containsKey(index)) {
			return -1;
		}
		if  (index != map.get(index) ) {
			map.put(index, this.parent(map.get(index)));
		}
		return map.get(index);
	}

	private int index(int i, int j, int k) {
		return i + j * n + k * m * n;
	}

	@Override
	public void debug4() {
		H.compare(4, this.regionsBySlashes(H.str2array2("[\"\\/\",\"/\\\"]")));
		H.compare(2, this.regionsBySlashes(H.str2array2("[\" /\",\"/ \"]")));
		H.compare(1, this.regionsBySlashes(H.str2array2("[\" /\",\"  \"]")));
		H.compare(5, this.regionsBySlashes(H.str2array2("[\"/\\\",\"\\/\"]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		
	}

}
